<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="工单编号" prop="workorderId">
                  <el-input v-model="queryParams.workorderId" placeholder="请输入工单编号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工单名称" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入工单名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="工单类型" prop="taskLevel">
                  <el-select v-model="queryParams.type">
                    <el-option v-for="item in workorderTypeList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="工单状态" prop="tag">
                  <el-select v-model="queryParams.status">
                    <el-option v-for="item in workorderStatusList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
                <el-col :span="8">
                  <el-form-item label="标星工单" prop="starStatus">
                    <el-select v-model="queryParams.starStatus">
                      <el-option v-for="item in workorderStarStatusList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              <el-col :span="8">
                <el-form-item label="工单标签" prop="tag">
                  <el-select v-model="queryParams.tag">
                    <el-option v-for="item in workorderTagList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker clearable
                    v-model="queryParams.startTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择开始时间"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker clearable
                    v-model="queryParams.endTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择结束时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['workorder:workorderInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['workorder:workorderInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['workorder:workorderInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['workorder:workorderInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="workorderInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工单编号" align="center" prop="workorderId" width="180" />
        <el-table-column label="工单名称" align="center" prop="name" width="180" />
        <el-table-column label="工单类型" align="center" prop="type" width="180">
          <template #default="scope">
            <span :style="{color: scope.row.type=='0'?'#67C23A':scope.row.type=='1'?'#F56C6C':scope.row.type=='2'?'#E6A23C': ''}">
              {{ scope.row.type=='0'?'保养工单':scope.row.type=='1'?'维修工单':scope.row.type=='2'?'巡检工单':'' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="报修时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工单状态" align="center" prop="status" width="180">
          <template #default="scope">
            <el-tag v-if="scope.row.status" :type="scope.row.status=='0'?'':scope.row.status=='1'?'':scope.row.status=='2'?'':scope.row.status=='3'?'success':''">
              {{ scope.row.status=='0'?'待处理':scope.row.status=='1'?'待执行':scope.row.status=='2'?'执行中':scope.row.status=='3'?'待确认':scope.row.status=='4'?'已完成':'' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="工单标签" align="center" prop="tag" width="180">
          <template #default="scope">
            <el-tag v-if="scope.row.tag" type="warning">
              {{ scope.row.tag=='11'?'已挂起':scope.row.tag=='12'?'已超时':'' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-tooltip v-if="scope.row.status=='0'" content="处理" placement="top">
                <el-button link type="primary" icon="ChatLineSquare" @click="handleUpdate(scope.row, 'process')" v-hasPermi="['workorder:workorderInfo:edit']"></el-button>
              </el-tooltip>
              <el-tooltip v-if="['1','2'].includes(scope.row.status)" content="执行" placement="top">
                <el-button link type="primary" icon="Check" @click="handleUpdate(scope.row, 'execute')" v-hasPermi="['workorder:workorderInfo:edit']"></el-button>
              </el-tooltip>
              <el-tooltip v-if="scope.row.status=='0' && scope.row.repairResult=='1' && scope.row.unFinishReason=='1'" content="确认来源" placement="top">
                <el-button link type="primary" icon="Pointer" @click="confirmSource(scope.row)" v-hasPermi="['workorder:workorderInfo:edit']"></el-button>
              </el-tooltip>
              <el-tooltip v-if="['0','1'].includes(scope.row.status) && !scope.row.pid" content="内容补录" placement="top">
                <el-button link type="primary" icon="EditPen" @click="handleUpdate(scope.row, 'supplement')" v-hasPermi="['workorder:workorderInfo:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['workorder:workorderInfo:remove']" style="color: red;"></el-button>
              </el-tooltip>
              <el-tooltip content="详情" placement="top">
                <el-button link type="primary" icon="view" @click="handleDetail(scope.row)" v-hasPermi="['workorder:workorderInfo:query']"></el-button>
              </el-tooltip>
              <el-tooltip v-if="['3'].includes(scope.row.status)" v-hasPermi="['workorder:workorderInfo:workorderFinish']" content="确认" placement="top">
                <el-button link type="primary" icon="CircleCheck" @click="handleConfirmation(scope.row)" v-hasPermi="['workorder:workorderInfo:query']" style="color: #b3e19d;"></el-button>
              </el-tooltip>
          </template>
<!--          <template #default="scope"  v-if="scope.row.type == '0'">-->
<!--            <el-tooltip v-if="scope.row.status=='0'" content="处理" placement="top">-->
<!--              <el-button link type="primary" icon="ChatLineSquare" @click="handleUpdate(scope.row, 'process')" v-hasPermi="['workorder:workorderInfo:edit']"></el-button>-->
<!--            </el-tooltip>-->

<!--          </template>-->
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改工单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="80%" append-to-body>
      <el-form ref="workorderInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col v-if="form.id" :span="24">
            <el-steps :active="activeStep" finish-status="success" simple style="margin-bottom: 10px;">
              <el-step v-for="item in workorderStatusList" :key="item.value" :title="item.label"></el-step>
            </el-steps>
          </el-col>
        </el-row>
        <el-row v-if="form.tagType!=='process'" :gutter="24">
          <el-col v-if="form.id" :span="12">
            <el-form-item label="工单编号" prop="workorderId">
              <el-input v-model="form.workorderId" :disabled="true" placeholder="请输入工单编号" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.id" :span="12">
            <el-form-item label="创建人" prop="createByName">
              <el-input v-model="form.createByName" :disabled="true" placeholder="请输入工单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入工单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="type">
              <el-select v-model="form.type">
                <el-option v-for="item in workorderTypeList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行区域" prop="execArea">
              <el-input v-model="form.execArea" placeholder="请输入执行区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统类型" prop="deviceSystem">
              <el-select v-model="form.deviceSystem" @change="deviceSystemHandle">
                <el-option v-for="item in deviceSystemList" :key="item.id" :value="item.id" :label="item.systemName"  placeholder="请选择系统类型"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '0'">
            <el-form-item label="保养事项" prop="bysx">
              <el-input v-model="form.bysx" placeholder="请输入保养事项" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '1'">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" :disabled="!form.deviceSystem">
                <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.typeName" placeholder="请选择设备类型"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '2'">
            <el-form-item label="巡检事项" prop="xjsx">
              <el-input v-model="form.xjsx" placeholder="请输入巡检事项" />
            </el-form-item>
          </el-col>


          <!-- <el-col :span="12">
            <el-form-item label="维修时间" prop="createTime">
              <el-date-picker clearable
                v-model="form.createTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="任务级别" prop="taskLevel">
              <el-select v-model="form.taskLevel">
                <el-option v-for="item in workorderTaskLevelList" :key="item.id" :value="item.value" :label="item.label" placeholder="请选择任务级别"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- <el-form-item label="工单备注" prop="baseRemark"> -->
            <el-form-item label="工单备注">
              <el-input type="textarea" v-model="form.baseRemark" placeholder="请输入工单备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.tagType=='process'" :gutter="24">
          <el-col :span="12">
            <el-form-item label="计划节点" prop="startTime">
              <el-date-picker v-model="dateRangeTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" @change="handleDateChange"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级别" prop="priorityLevel">
              <el-select v-model="form.priorityLevel">
                <el-option v-for="item in taskLevelList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员分配" prop="userIdList">
              <MySelectionInput v-if="type" v-model="form.userIdList" :form-rules="rules" :type="type" @change="handleSelectionChange" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划备注">
              <el-input type="textarea" v-model="form.planRemark" placeholder="请输入工单备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现场协助">
              <el-input v-model="form.locationSupport" placeholder="请输入现场协助" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <ProjectFormDialog v-model:visible="dialogProjectFormVisible" @close="closeDialog"  @call-parent-method="getList" /> -->
    <MyWorkOrderDialog v-if="activeStep || workorderId"
      v-model:visible="dialogWorkOrderVisible"
      v-model:title="dialogTitle"
      :workorderId="workorderId"
      :activeStep="activeStep"
      :initialData="form"
      :workorderStatusList="workorderStatusList"
      :workorderPartsList="workorderPartsList"
      :key="componentKey"
      @close="closeDialog"
      @call-parent-method="getList" />
    <el-dialog title="备件来源" v-model="dialog.addPartsBatchVisible" width="80%" append-to-body>
      <!-- <el-table :data="partsBatchTableData" style="width: 100%"  @selection-change="handleSelectionChange"> -->
      <el-table :data="partsBatchTableData" style="width: 100%">
        <el-table-column label="设备系统" align="center" prop="deviceSystem">
          <template #default="scope">
            <span>{{ getDeviceSystemName(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center" prop="deviceType" >
          <template #default="scope">
            <span>{{ getDeviceTypeName(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="厂家" align="center" prop="factory" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="型号" align="center" prop="model" />
        <el-table-column label="规格" align="center" prop="specifications" />
        <el-table-column label="数量" align="center" prop="number" />
        <el-table-column label="来源" align="center" prop="source">
          <template #default="scope">
            <span>{{ getSourceName(scope.row) }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="状态" align="center" prop="status" />-->
<!--        <el-table-column label="工单id" align="center" prop="workorderId" />-->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-tooltip content="选择来源" placement="top">
              <el-button link type="primary" icon="Edit" @click="handlePartsRequipment(scope.row)" v-hasPermi="['workorder:partsRequipment:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="备件来源" v-model="dialog.updateVisible" width="80%" append-to-body>
      <!-- {{ partsRequipmentForm.value }} -->
      <!-- <el-form ref="partsRequipmentFormRef" :model="partsRequipmentForm" :rules="partsRequipmentRules" label-width="120px"> -->
        <el-form ref="partsRequipmentFormRef" :model="partsRequipmentForm" label-width="120px">
        <el-row :guuter="24">
          <el-col :span="12">
            <el-form-item label="工单id" prop="workorderId">
              <el-input v-model="partsRequipmentForm.value.workorderId" placeholder="请输入工单id" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件来源" prop="source">
              <el-select v-model="partsRequipmentForm.value.source" placeholder="请选择备件来源" required>
                <el-option v-for="item in sourceList" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统类型" prop="deviceSystem">
              <el-select v-model="partsRequipmentForm.value.deviceSystem" @change="deviceSystemHandle" placeholder="请选择系统类型" required>
                <el-option v-for="item in deviceSystemList" :key="item.id" :value="item.id" :label="item.systemName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="partsRequipmentForm.value.deviceType" :disabled="!partsRequipmentForm.value.deviceSystem" placeholder="请选择设备类型" required>
                <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.typeName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家" prop="factory">
              <el-input v-model="partsRequipmentForm.value.factory" placeholder="请输入厂家" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="partsRequipmentForm.value.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="partsRequipmentForm.value.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="partsRequipmentForm.value.specifications" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="number">
              <el-input v-model="partsRequipmentForm.value.number" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="partsRequipmentForm.value.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="partsRequipmentCancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="partsRequipmentSubmitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="查看详情" v-model="dialogDetailWorkOrderVisible" width="80%" append-to-body>
      <!-- workorderProcessVoList: {{  detailForm.workorderProcessVoList  }} <br />  -->
      <!-- workorderPartsyoList: {{  detailForm.workorderPartsVoList  }} <br /> -->
      <!-- childWorkorderList: {{  detailForm.childWorkorderList  }} -->
      <template v-for="detailForm in detailFormList" >
        <el-form ref="detailFormRef" :model="detailForm" label-width="100px">
          <el-row :guuter="24">
            <el-col :span="24">
              <div class="table-header-info">
                <h3 class="table-name">工单详情信息</h3>
              </div>
            </el-col>
            <el-col v-if="detailForm.workorderId" :span="12">
              <el-form-item label="工单编号" prop="workorderId">
                <el-input v-model="detailForm.workorderId" :disabled="true" placeholder="请输入工单编号" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.name" :span="12">
              <el-form-item label="工单名称" prop="name">
                <el-input v-model="detailForm.name" :disabled="true" placeholder="请输入工单名称" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.type" :span="12">
              <el-form-item label="工单类型" prop="type">
                <el-select v-model="detailForm.type" :disabled="true">
                  <el-option v-for="item in workorderTypeList" :key="item.id" :value="item.value" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.execArea" :span="12">
              <el-form-item label="执行区域" prop="execArea">
                <el-input v-model="detailForm.execArea" :disabled="true" placeholder="请输入执行区域" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.deviceSystem" :span="12">
              <el-form-item label="系统类型" prop="deviceSystem">
                <el-select v-model="detailForm.deviceSystem" @change="deviceSystemHandle" :disabled="true">
                  <el-option v-for="item in deviceSystemList" :key="item.id" :value="item.id" :label="item.systemName"  placeholder="请选择系统类型"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.type == '0' && detailForm.bysx":span="12">
              <el-form-item label="保养事项" prop="bysx">
                <el-input v-model="detailForm.bysx" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.type == '1' && detailForm.deviceType" :span="12">
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="detailForm.deviceType" :disabled="true">
                  <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.typeName" placeholder="请选择设备类型"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.type == '2' && detailForm.xjsx"  :span="12">
              <el-form-item label="巡检事项" prop="xjsx">
                <el-input v-model="detailForm.xjsx" :disabled="true" />
              </el-form-item>
            </el-col>

            <el-col v-if="detailForm.taskLevel" :span="12">
              <el-form-item label="任务级别" prop="taskLevel">
                <el-select v-model="detailForm.taskLevel" :disabled="true">
                  <el-option v-for="item in workorderTaskLevelList" :key="item.id" :value="item.value" :label="item.label" placeholder="请选择任务级别"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.status" :span="12">
              <el-form-item label="工单状态" prop="tag">
                <el-select v-model="detailForm.status" :disabled="true">
                  <el-option v-for="item in workorderStatusList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.baseRemark" :span="24">
              <el-form-item label="工单备注">
                <el-input type="textarea" v-model="detailForm.baseRemark" :disabled="true" placeholder="请输入工单备注" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.tag" :span="12">
              <el-form-item label="工单标签" prop="tag">
                <el-select v-model="detailForm.tag" :disabled="true">
                  <el-option v-for="item in workorderTagList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.startTime" :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker clearable
                                v-model="detailForm.startTime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择开始时间"
                                :disabled="true"
                                style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.endTime" :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker clearable
                                v-model="detailForm.endTime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择结束时间"
                                :disabled="true"
                                style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.priorityLevel" :span="12">
              <el-form-item label="优先级别" prop="priorityLevel">
                <el-select v-model="detailForm.priorityLevel" :disabled="true">
                  <el-option v-for="item in taskLevelList" :key="item.id" :value="item.value" :label="item.label"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.userIdList" :span="12">
              <el-form-item label="人员分配" prop="userIdList">
                <MySelectionInput v-if="type" v-model="detailForm.userIdList" :form-rules="rules" :type="type" @change="handleSelectionChange" :disabled="true" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.planRemark" :span="12">
              <el-form-item label="计划备注">
                <el-input type="textarea" v-model="detailForm.planRemark" :disabled="true" placeholder="请输入工单备注" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.locationSupport" :span="12">
              <el-form-item label="现场协助">
                <el-input v-model="detailForm.locationSupport" :disabled="true" placeholder="请输入现场协助" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.problemDescription" :span="12">
              <el-form-item label="问题描述">
                <el-input type="textarea" v-model="detailForm.problemDescription" :disabled="true" placeholder="请输入问题描述" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.reason" :span="12">
              <el-form-item label="故障原因">
                <el-input type="textarea" v-model="detailForm.reason" :disabled="true" placeholder="请输入故障原因" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.handMethod" :span="12">
              <el-form-item label="处理办法">
                <el-input v-model="detailForm.handMethod" :disabled="true" placeholder="请输入处理办法" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.fwtd" :span="12">
              <el-form-item label="服务态度">
                <el-input v-model="detailForm.fwtd" :disabled="true" placeholder="请输入服务态度" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.jsnl" :span="12">
              <el-form-item label="技术能力">
                <el-input v-model="detailForm.jsnl" :disabled="true" placeholder="请输入技术能力" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.xysd" :span="12">
              <el-form-item label="响应速度">
                <el-input v-model="detailForm.xysd" :disabled="true" placeholder="请输入响应速度" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.fwpj" :span="12">
              <el-form-item label="服务评价描述">
                <el-input type="textarea" v-model="detailForm.fwpj" :disabled="true" placeholder="请输入服务评价描述" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.pjdj" :span="12">
              <el-form-item label="评价等级">
                <el-input v-model="detailForm.pjdj" :disabled="true" placeholder="请输入评价等级" />
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.repairResult" :span="12">
              <el-form-item label="维修结果" prop="repairResult">
                <el-select v-model="detailForm.repairResult" placeholder="请选择维修结果" :disabled="true">
                  <el-option v-for="item in repairResultList" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.unFinishReason" :span="12">
              <el-form-item label="未完成原因" prop="reason">
                <el-select v-model="detailForm.unFinishReason" placeholder="请选择未完成原因" :disabled="true">
                  <el-option v-for="item in reasonList" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.professionalAdvice" :span="12">
              <el-form-item label="专业建议" prop="professionalAdvice">
                <el-input v-model="detailForm.professionalAdvice" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.propertyReport" :span="12">
              <el-form-item label="物业汇报" prop="propertyReport">
                <el-input v-model="detailForm.propertyReport" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="detailForm.picPath" :span="form.repairResult=='1'?24:12">
              <el-form-item label="维修照片" prop="picPath">
                <imageUpload v-model="detailForm.picPath" :type="'pic'" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="detailForm.workorderPartsVoList&&detailForm.workorderPartsVoList.length>0" :guuter="24">
            <el-col :span="24">
              <div class="table-header-info">
                <h3 class="table-name">工单备件信息</h3>
              </div>
            </el-col>
            <el-col :span="24">
              <el-col v-for="(item, index) in detailForm.workorderPartsVoList" :key="index" :span="24" style="margin-bottom: 20px; padding-right: 20px; border: 1px dashed #c0c0c0; padding: 20px 0;">
                <MyAccessoryItem :accessory="item" :disabled="true" />
              </el-col>
            </el-col>
          </el-row>
          <el-row v-if="detailForm.workorderProcessVoList&&detailForm.workorderProcessVoList.length>0" :guuter="24">
            <el-col :span="24">
              <div class="table-header-info">
                <h3 class="table-name">工单流程信息</h3>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="workflow-container">
                <el-steps :active="activeStepData" direction="vertical" align-center>
                  <!-- <el-step
                    v-for="(item, index) in detailForm.workorderProcessVoList"
                    :key="item.id"
                    :title="item.workorderName || '未命名工单'"
                    :description="formatDescription(item)"
                    :status="getStatus(item.status)"
                    style="line-height: 50px;"
                  > -->
                  <el-step
                    v-for="(item, index) in detailForm.workorderProcessVoList"
                    :key="item.id"
                    :title="item.workorderName || '未命名工单'"
                    :description="formatDescription(item)"
                    style="line-height: 80px;"
                  >
                    <!-- <template #icon>
                      <el-icon v-if="item.status === '0'" color="#f56c6c"><CircleClose /></el-icon>
                      <el-icon v-else-if="item.status === '1'" color="#e6a23c"><Edit /></el-icon>
                      <el-icon v-else-if="item.status === '2'" color="#67c23a"><SuccessFilled /></el-icon>
                    </template> -->
                  </el-step>
                </el-steps>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>

    </el-dialog>
    <!-- 评价 -->
    <el-dialog title="评价工单" v-model="evaluationPopupVisible" width="80%" append-to-body>
        <el-form :model="evaluationPopupForm" label-width="120px">
          <el-form-item label="服务态度">
              <el-rate v-model="evaluationPopupForm.fwtd" :max="5"  text-color="#ff9900" allow-half></el-rate>
          </el-form-item>
          <el-form-item label="技术能力">
              <el-rate v-model="evaluationPopupForm.jsnl" :max="5"   text-color="#ff9900" allow-half></el-rate>
          </el-form-item>
          <el-form-item label="响应速度">
              <el-rate v-model="evaluationPopupForm.xysd" :max="5"   text-color="#ff9900" allow-half></el-rate>
          </el-form-item>
          <el-form-item label="服务评价描述">
            <el-input type="textarea" placeholder="请输入您的评价" v-model="evaluationPopupForm.fwpj"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="evaluationPopupVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="WorkorderInfo" lang="ts">
import { listWorkorderParts, workorderParts2partsRequipment, getDetailWorkorderParts } from '@/api/workorder/workorderParts';
import {
  listWorkorderInfo,
  getWorkorderInfo,
  delWorkorderInfo,
  addWorkorderInfo,
  updateWorkorderInfo,
  getStartExecute,
  workorderConfirm
} from '@/api/workorder/workorderInfo';
import { WorkorderInfoVO, WorkorderInfoQuery, WorkorderInfoForm } from '@/api/workorder/workorderInfo/types';
import { PartsRequipmentVO, PartsRequipmentForm } from '@/api/workorder/partsRequipment/types';
import { getPartsRequipment, updatePartsRequipment, partsRequipmentSave } from '@/api/workorder/partsRequipment';
import { listDeviceSystem } from '@/api/workorder/deviceSystem';
import { listDeviceType } from '@/api/workorder/deviceType';
import SelectionInput from '../../components/selectionInput.vue';
import WorkOrderDialog from '../../components/workOrderDialog.vue';
import AccessoryItem from '../../components/accessoryItem.vue';
import { format } from 'date-fns';
import { listUser } from '@/api/system/user';
import Cookies from 'js-cookie';
import { addWorkorderPartsBatch } from '@/api/workorder/partsRequipment';
import MyAccessoryItem from '../../components/accessoryItem.vue';
const route = useRoute();
const router = useRouter();
const MySelectionInput = SelectionInput;
const MyWorkOrderDialog = WorkOrderDialog;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface WorkorderInfoVO {
  id: string | number | undefined;
  workorderId: string | number | undefined;
  createByName: string | undefined;
  name: string | undefined;
  type: string | number | undefined;
  execArea: string | undefined;
  deviceSystem: string | number | undefined;
  deviceType: string | number | undefined;
  taskLevel: string | number | undefined;
  baseRemark: string | undefined;
  status: string | number | undefined;
  tag: string | number | undefined;
  createTime: string | undefined;
  startTime: string | undefined;
  endTime: string | undefined;
  priorityLevel: string | number | undefined;
  userIdList: Array<string | number> | undefined;
  userNames: Array<string> | undefined;
  planRemark: string | undefined;
  locationSupport: string | undefined;
  problemDescription: string | undefined;
  reason: string | undefined;
  handMethod: string | undefined;
  fwtd: string | undefined;
  jsnl: string | undefined;
  xysd: string | undefined;
  fwpj: string | undefined;
  pjdj: string | undefined;
  starStatus: string | undefined;
  tagType: string | undefined;
}

interface WorkorderInfoQuery {
  pageNum: number;
  pageSize: number;
  workorderId?: string | number;
  name?: string;
  type?: string | number;
  execArea?: string;
  deviceSystem?: string | number;
  deviceType?: string | number;
  taskLevel?: string | number;
  baseRemark?: string;
  status?: string | number;
  tag?: string | number;
  startTime?: string;
  endTime?: string;
  priorityLevel?: string | number;
  userIdList?: Array<string | number>;
  userNames?: Array<string>;
  planRemark?: string;
  locationSupport?: string;
  problemDescription?: string;
  reason?: string;
  handMethod?: string;
  fwtd?: string;
  jsnl?: string;
  xysd?: string;
  fwpj?: string;
  pjdj?: string;
  starStatus?: string;
  params?: Record<string, any>;
}

interface DeviceSystemParams {
  pageNum: number;
  pageSize: number;
  description?: string;
  systemId?: string | number;
}

interface WorkorderInfoForm extends WorkorderInfoVO {}

interface DialogOption {
  visible: boolean;
  title: string;
}

interface PageData<Form, Query> {
  form: Form;
  queryParams: Query;
  deviceSystemParams: DeviceSystemParams;
  rules: Record<string, Array<{ required: boolean; message: string; trigger: string }>>;
}

const type = ref('info');
const projectId = Cookies.get('projectId');
const formType = ref(null);
const activeStep = ref(0);
const dateRangeTime = ref<[Date | null, Date | null]>([null, null]);
const userItemList = ref([]);
const dialogWorkOrderVisible = ref(false);
const dialogTitle = ref(null);
const partsBatchTableData = ref<PartsRequipmentVO[]>([]);
const partsRequipmentForm: PartsRequipmentForm = {
  id: undefined,
  deviceSystem: undefined,
  deviceType: undefined,
  factory: undefined,
  brand: undefined,
  model: undefined,
  specifications: undefined,
  number: undefined,
  source: undefined,
  status: undefined,
  workorderId: undefined,
  remark: undefined
}
const partsRequipmentRules = {
  id: [
    { required: true, message: "id不能为空", trigger: "blur" }
  ],
  workorderId: [
    { required: true, message: "工单编号不能为空", trigger: "blur" }
  ],
  deviceSystem: [
    { required: true, message: "设备系统不能为空", trigger: "blur" }
  ],
  // deviceType: [
  //   { required: true, message: "设备类型不能为空", trigger: "change" }
  // ],
  source: [
    { required: true, message: "备件来源不能为空", trigger: "change" }
  ],
  factory: [
    { required: true, message: "厂家不能为空", trigger: "blur" }
  ],
  brand: [
    { required: true, message: "品牌不能为空", trigger: "blur" }
  ],
  model: [
    { required: true, message: "型号不能为空", trigger: "blur" }
  ],
  specifications: [
    { required: true, message: "规格不能为空", trigger: "blur" }
  ],
  number: [
    { required: true, message: "数量不能为空", trigger: "blur" }
  ]
};
const partsRequipmentFormRef = ref(null);

const workorderTypeList = ref([
  { id: 0, label: '保养工单', value: '0' },
  { id: 1, label: '维修工单', value: '1' },
  { id: 2, label: '巡检工单', value: '2' }
]);

const workorderStatusList = ref([
  { id: 0, label: '待处理', value: '0' },
  { id: 1, label: '待执行', value: '1' },
  { id: 2, label: '执行中', value: '2' },
  { id: 3, label: '待确认', value: '3' },
  { id: 4, label: '已完成', value: '4' },
  { id: 15, label: '实时工单', value: '15' }
]);
const workorderStarStatusList = ref([
  { id: 0, label: '否', value: '0' },
  { id: 1, label: '是', value: '1' }
]);


const workorderTagList = ref([
  { id: 0, label: '已挂起', value: '11' },
  { id: 1, label: '已超时', value: '12' }
]);

const workorderTaskLevelList = ref([
  { id: 0, label: '重大', value: '0' },
  { id: 1, label: '紧急', value: '1' },
  { id: 2, label: '普通', value: '2' }
]);

const taskLevelList = ref([
  { id: 0, label: '紧急 ', value: '0' },
  { id: 1, label: '优先', value: '1' },
  { id: 2, label: '正常', value: '2' }
]);

const sourceList = readonly(ref<RepairResult[]>([{ id: '01', label: '甲供待采', value: '0'},{ id: '02', label: '备件待采', value: '1'}]));
const repairResultList = readonly(ref<RepairResult[]>([{ label: '完成', value: '0'},{ label: '未完成', value: '1'}]));
const reasonList = readonly(ref<RepairResult[]>([{ label: '任务升级', value: '0'},{ label: '备件待采', value: '1'}]));
const sparePartsSourceList = readonly(ref<RepairResult[]>([{ label: '甲供待采', value: '0'},{ label: '备件待采', value: '1'}]));

const dialog = reactive<DialogOption>({
  visible: false,
  addPartsBatchVisible: false,
  updateVisible: false,
  title: ''
});

const initFormData: WorkorderInfoForm = {
  id: undefined,
  workorderId: undefined,
  createByName: undefined,
  name: undefined,
  type: undefined,
  execArea: undefined,
  deviceSystem: undefined,
  deviceType: undefined,
  taskLevel: undefined,
  baseRemark: undefined,
  status: undefined,
  statusList: undefined,
  tag: undefined,
  createTime: undefined,
  startTime: undefined,
  endTime: undefined,
  priorityLevel: undefined,
  userIdList: undefined,
  userNames: undefined,
  planRemark: undefined,
  locationSupport: undefined,
  problemDescription: undefined,
  reason: undefined,
  handMethod: undefined,
  fwtd: undefined,
  jsnl: undefined,
  xysd: undefined,
  fwpj: undefined,
  pjdj: undefined,
  starStatus: undefined,
  tagType: undefined,
  bynr: undefined,
  bysx: undefined,
  xjnr: undefined,
  xjsx: undefined,
};

const data = reactive<PageData<WorkorderInfoForm, WorkorderInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workorderId: undefined,
    name: undefined,
    type: undefined,
    execArea: undefined,
    deviceSystem: undefined,
    deviceType: undefined,
    taskLevel: undefined,
    baseRemark: undefined,
    status: undefined,
    tag: undefined,
    startTime: undefined,
    endTime: undefined,
    priorityLevel: undefined,
    userIdList: undefined,
    userNames: undefined,
    planRemark: undefined,
    locationSupport: undefined,
    problemDescription: undefined,
    reason: undefined,
    handMethod: undefined,
    fwtd: undefined,
    jsnl: undefined,
    xysd: undefined,
    fwpj: undefined,
    pjdj: undefined,
    starStatus: undefined,
    params: {}
  },
  deviceSystemParams: {
    pageNum: 1,
    pageSize: 999,
    description: undefined,
    systemId: undefined
  },
  rules: {
    id: [{ required: true, message: "Id不能为空", trigger: "blur" }],
    workorderId: [{ required: true, message: "工单编号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "工单名称不能为空", trigger: "blur" }],
    type: [{ required: true, message: "工单类型不能为空", trigger: "change" }],
    execArea: [{ required: true, message: "执行区域不能为空", trigger: "blur" }],
    deviceSystem: [{ required: true, message: "设备系统不能为空", trigger: "blur" }],
    // deviceType: [{ required: true, message: "设备类型不能为空", trigger: "change" }],
    taskLevel: [{ required: true, message: "任务级别不能为空", trigger: "blur" }],
    baseRemark: [{ required: true, message: "工单备注不能为空", trigger: "blur" }],
    status: [{ required: true, message: "工单状态(大状态)不能为空", trigger: "change" }],
    tag: [{ required: true, message: "工单标签(小状态)不能为空", trigger: "blur" }],
    createTime: [{ required: true, message: "维修时间不能为空", trigger: "blur" }],
    startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
    endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
    priorityLevel: [{ required: true, message: "优先级别不能为空", trigger: "blur" }],
    userIdList: [{ required: true, message: "请选择分配人员", trigger: ["blur", "change"] }],
    userNames: [{ required: true, message: "分配人员姓名不能为空", trigger: "blur" }],
    planRemark: [{ required: true, message: "计划备注不能为空", trigger: "blur" }],
    locationSupport: [{ required: true, message: "现场协助不能为空", trigger: "blur" }],
    problemDescription: [{ required: true, message: "问题描述不能为空", trigger: "blur" }],
    reason: [{ required: true, message: "故障原因不能为空", trigger: "blur" }],
    handMethod: [{ required: true, message: "处理办法不能为空", trigger: "blur" }],
    fwtd: [{ required: true, message: "服务态度不能为空", trigger: "blur" }],
    jsnl: [{ required: true, message: "技术能力不能为空", trigger: "blur" }],
    xysd: [{ required: true, message: "响应速度不能为空", trigger: "blur" }],
    fwpj: [{ required: true, message: "服务评价描述不能为空", trigger: "blur" }],
    pjdj: [{ required: true, message: "评价等级不能为空", trigger: "blur" }],
    starStatus: [{ required: true, message: "是否是标星工单不能为空", trigger: "change" }]
  }
});

const workorderInfoList = ref<WorkorderInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deviceSystemList = ref<Array<{ id: string | number, systemName: string }>>([]);
const deviceTypeList = ref<Array<{ id: string | number, typeName: string }>>([]);
const queryFormRef = ref<ElFormInstance>();
const workorderInfoFormRef = ref<ElFormInstance>();
const workorderId = ref(null);
const resetParams = ref(null);
const workorderPartsList = ref<Array<string | number>>([]);
// 定义一个响应式变量作为 key
const componentKey = ref(0);
const detailForm = ref({});
const detailFormList = ref<WorkorderInfoVO[]>([]);
const dialogDetailWorkOrderVisible = ref(false);

const handleDateChange = (value: [Date | null, Date | null]) => {
  if (value && value.length === 2) {
    form.value.startTime = computed(() => value[0] ? format(new Date(value[0]), 'yyyy-MM-dd HH:mm:ss') : '');
    form.value.endTime = computed(() => value[1] ? format(new Date(value[1]), 'yyyy-MM-dd HH:mm:ss') : '');
  }
};

const { queryParams, deviceSystemParams, form, rules } = toRefs(data);

const getDeviceSystemList = async () => {
  const res = await listDeviceSystem(deviceSystemParams.value);
  deviceSystemList.value = res.rows;
};

const getDeviceTypeList = async () => {
  deviceSystemParams.value.systemId = form.value.deviceSystem;
  const res = await listDeviceType(deviceSystemParams.value);
  deviceTypeList.value = res.rows;
};

const deviceSystemHandle = () => {
  form.value.deviceType = ref(null);
  getDeviceTypeList();
};

const getList = async () => {
  loading.value = true;
  queryParams.value.projectId = projectId;
  if (resetParams.value!=='reset') {
    queryParams.value.type = queryParams.value.type?queryParams.value.type:route.query.type;
    queryParams.value.status = queryParams.value.status?queryParams.value.status:route.query.status;
    queryParams.value.starStatus = queryParams.value.starStatus?queryParams.value.starStatus:route.query.starStatus;
    queryParams.value.tag = queryParams.value.tag?queryParams.value.tag:route.query.tag;
  } else {
    queryParams.value.type = queryParams.value.type?queryParams.value.type:null;
  }
  try {
    const res = await listWorkorderInfo(queryParams.value);
    workorderInfoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const getListForRouter = async () => {
  loading.value = true;
  queryParams.value.projectId = projectId;
  if (resetParams.value!=='reset') {
    queryParams.value.type = route.query.type;
    queryParams.value.status = route.query.status;
    queryParams.value.starStatus = route.query.starStatus;
    queryParams.value.tag = route.query.tag;
  } else {
    queryParams.value.type = queryParams.value.type?queryParams.value.type:null;
  }
  try {
    const res = await listWorkorderInfo(queryParams.value);
    workorderInfoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData };
  workorderInfoFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  resetParams.value = 'reset';
  queryParams.value.type = null;
  queryParams.value.status = null;
  queryParams.value.tag = null;
  queryParams.value.startTime = null;
  queryParams.value.endTime = null;
  handleQuery();
};

const handleSelectionChange = (selection: WorkorderInfoVO[]) => {
  form.value.userIdList = selection;
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加工单信息";
  formType.value = 'add';
};

const handleUpdate = async (row?: WorkorderInfoVO, type?: string) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getWorkorderInfo(_id);
  Object.assign(form.value, res.data);
  activeStep.value = Number(form.value.status);
  workorderId.value = _id;
  if (type === 'execute') {
    componentKey.value += 1; // 更新 key 值
    if (form.value.status!=='2') {
      const startExecuteRes = await getStartExecute(_id);
      if (!startExecuteRes.data.status) return;
      if (startExecuteRes.data.status) {
        activeStep.value =  Number(startExecuteRes.data.status);
      }
    }else if (form.value.status=='2') {
      workorderPartsList.value = [];
      const listWorkorderRes = await listWorkorderParts({pageNum: 1, pageSize: 999, workorderId: _id});
      workorderPartsList.value = listWorkorderRes.rows;
    }
    if(form.value.type == '0'){
      dialogTitle.value = "保养工作";
    }else if(form.value.type == '1'){
      dialogTitle.value = "维修执行";
    }else if(form.value.type == '2'){
      dialogTitle.value = "巡检工作";
    }
    dialogWorkOrderVisible.value = true;
  } else {
    await getDeviceTypeList();
    dialog.visible = true;
    form.value.tagType = type ?? 'edit';
    dialog.title = type === 'process' ? '处理工单信息' : type === 'supplement' ? '补录工单信息' : '修改工单信息';
  }
};

const confirmSource = async (row?: WorkorderInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await workorderParts2partsRequipment(_id);
  partsBatchTableData.value = res.data
  dialog.addPartsBatchVisible = true;
  getDeviceTypeList();
  //todo 弹框展示返回的备件需求数据，可在弹框内修改来源字段
  //todo 修改完之后，将备件需求数据回传至提交接口,下方是为了测试接口
  //todo 添加完之后，备件需求页面就可以展示了，在备件需求页面记得将 设备系统和设备类型进行回显
  console.log(res)
};

const handlePartsRequipment = async (row?: PartsRequipmentVO) => {
  reset();
  // const _id = row?.id || ids.value[0]
  // const res = await getPartsRequipment(_id);
  partsRequipmentForm.value = row;
  // Object.assign(partsRequipmentForm.value, row.value);
  dialog.updateVisible = true;
}

const handleDetail = async (row?: WorkorderInfoVO) => {
  detailFormList.value = [];
  const _ids = row?.workorderId || ids.value;
  try {
    const _workorderId= row?.workorderId || ids.value[0];
    const res = await getDetailWorkorderParts(_workorderId);
    detailFormList.value.push(res.data);
    Object.assign(detailForm.value, res.data);
    if(res.data.childWorkorderList && res.data.childWorkorderList.length>0){
      res.data.childWorkorderList.forEach(item=>{
        detailFormList.value.push(item);
      })
      Object.assign(detailForm.value, res.data.childWorkorderList[res.data.childWorkorderList.length -1]);
    }
    // workorderPartsList.value = await listWorkorderParts({pageNum: 1, pageSize: 999, workorderId: _id});
    // dialogWorkOrderVisible.value = true;
    dialogDetailWorkOrderVisible.value = true;
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};
// 定义弹窗状态和表单数据
const evaluationPopupVisible = ref(false);
const evaluationPopupForm = reactive({
  fwtd: 5, // 服务态度，默认五星
  jsnl: 5, // 技术能力，默认五星
  xysd: 5, // 响应速度，默认五星
  fwpj: ''   // 服务评价
});
const evaluationRows = reactive({}); // 当前行数据

// 打开弹窗并初始化数据
const handleConfirmation = (row?: WorkorderInfoVO) => {
  if (row) {
    Object.assign(evaluationRows, row); // 使用 Object.assign 避免直接覆盖引用
  }
  evaluationPopupVisible.value = true; // 显示弹窗
};
// 提交评价
const submitEvaluation = async () => {
  try {
    evaluationRows.fwtd = evaluationPopupForm.fwtd;
    evaluationRows.jsnl = evaluationPopupForm.jsnl;
    evaluationRows.xysd = evaluationPopupForm.xysd;
    evaluationRows.fwpj = evaluationPopupForm.fwpj;

    // console.log(evaluationRows, 'evaluationRows');
    const res = await workorderConfirm(evaluationRows);
    if (res.code === 200) {
      ElMessage({
        message: '工单确认及评价成功！',
        type: 'success'
      });
      evaluationPopupVisible.value = false; // 关闭弹窗
      resetForm(); // 重置表单
      getList();
    } else {
      ElMessage({
        message: res.msg || '提交失败，请稍后重试',
        type: 'warning'
      });
    }
  } catch (error) {
    ElMessage({
      message: '网络错误，请稍后重试',
      type: 'error'
    });
  }
};

// 重置表单数据
const resetForm = () => {
  evaluationPopupForm.fwtd = '5';
  evaluationPopupForm.jsnl = '5';
  evaluationPopupForm.xysd = '5';
  evaluationPopupForm.fwpj = '';
  Object.keys(evaluationRows).forEach(key => {
    delete evaluationRows[key]; // 清空行数据
  });
};

const submitForm = () => {
  workorderInfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;
    form.value.projectId = projectId;
    if (form.value.tagType === 'process') {
      dateRangeTime.value = ref<[Date | null, Date | null]>([null, null]);
      form.value.status = '1';
      form.value.userNames = userItemList.value.filter(user => form.value.userIdList.includes(user.userId)).map(user => user.nickName).join(',');
    }
    try {
      if (form.value.id) {
        await updateWorkorderInfo(form.value);
      } else {
        await addWorkorderInfo(form.value);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    } catch (error) {
      console.error(error);
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: WorkorderInfoVO) => {
  const _ids = row?.id || ids.value;
  try {
    await proxy?.$modal.confirm(`是否确认删除工单信息编号为"${_ids}"的数据项？`);
    await delWorkorderInfo(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const handleExport = () => {
  proxy?.download('workorder/workorderInfo/export', {
    ...queryParams.value
  }, `workorderInfo_${new Date().getTime()}.xlsx`);
};

const closeDialog = () => {
  dialogWorkOrderVisible.value = false;
};

// 用户数据
async function fetchUserItems() {
  let params = {
    pageNum: 1,
    pageSize: 999
  }
  try {
    listUser(params).then(data => {
      userItemList.value = data.rows;
      // console.log(userItemList.value, 'userItemList')
    })
  } catch (error) {
    console.error(error);
  }
};

const getDeviceSystemName = (row?: PartsRequipmentVO) => {
  const deviceSystem = deviceSystemList.value.find(item => item.id === row?.deviceSystem);
  return deviceSystem ? deviceSystem.systemName : '';
};
const getDeviceTypeName = (row?: PartsRequipmentVO) => {
  // console.log(deviceTypeList.value, row, 'deviceTypeList.value')
  const deviceType = deviceTypeList.value.find(item => item.id === row?.deviceType);
  return deviceType ? deviceType.typeName : '';
};
const getSourceName = (row?: PartsRequipmentVO) => {
  const sourceType = sourceList.value.find(item => item.value === row?.source);
  return sourceType ? sourceType.label : '';
};
/** 取消按钮 */
const partsRequipmentCancel = () => {
  reset();
  dialog.updateVisible = false;
};
// 确定
const partsRequipmentSubmitForm = () => {
  partsRequipmentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await partsRequipmentSave(partsRequipmentForm.value);
      proxy?.$modal.msgSuccess("操作成功");
      dialog.updateVisible = false;
      await getList();
    }
  });
};
// 格式化描述信息
const formatDescription = (item) => {
  return `${item.remark} (${new Date().toLocaleString()})`;
};
const getStatus = (status) => {
  // switch (status) {
  //   case '0':
  //     return 'error'; // 错误状态
  //   case '1':
  //     return 'process'; // 进行中状态
  //   case '2':
  //     return 'success'; // 成功状态
  //   default:
  //     return 'wait'; // 等待状态
  // }
};
// 当前激活的步骤
const activeStepData = computed(() => {
  // const lastCompletedIndex = detailForm.value.workorderProcessVoList.findIndex(item => item.status === '2');
  // return lastCompletedIndex !== -1 ? lastCompletedIndex : 0;
  return detailForm.value.workorderProcessVoList.length
});

watch( () => route.query, (newPath, oldPath) => {
  // if (newPath.type == 1) {
  //   console.log(newPath.type, "报修");
  // } else if (newPath.type == 0 ){
  //   console.log(newPath.type, "保养");
  // }
  // console.log(111,newPath.type);
  getListForRouter();
} );

onMounted(() => {
  getList();
  getDeviceSystemList();
  fetchUserItems();
});

</script>
<style scoped>
.workflow-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
}
</style>
